/*
 * @Author: MrLee
 * @Date: 2024-09-09 16:52:11
 * @LastEditors: MrLee
 * @LastEditTime: 2024-09-10 14:54:05
 * @Description: 请填写简介
 */
import { defineStore } from 'pinia';
import type { UserState, providerType } from './types';
import { clearToken } from '@/utils/auth';
import {userLogin, userUserInfo, WxLogin} from '@/api/user';
import type { UserUserInfoResult } from '@/api/user/types';

type ClientType = 'customer' | 'enterprise' | '';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    role: 'customer',
    token: '',
    tokenType: '',
    expires: Infinity,
    info: reactive<Partial<UserUserInfoResult>>({
      id: 0,
      name: '',
      avatar: '',
      password: '',
      status: 0,
      phone: 0,
      type: 0,
      openid_mini: '',
      created_at: '',
      updated_at: '',
      deleted_at: null,
      company_id: 0,
      gender: '',
      job_status: 0,
      province_id: null,
      city_id: 0,
      age: 0,
      political_outlook: 0,
      born: 0,
      email: '',
      last_education_id: 0,
      last_resume_id: 0,
      school: {
        id: 0,
        name: '',
      },
      province: null,
      city: {
        id: 0,
        name: '',
      },
    }),
  }),
  getters: {
    // 客户端状态
    clientType(state: UserState): ClientType {
      const clientType: ClientType = 'customer';
      // type: 用户角色 [1普通用户] [2老师] [3公司-主管] [4公司-HR]'
      const type = state.info.type;
      if (typeof type === 'number') {
        return type === 1 ? 'customer' : [3, 4].includes(type) ? 'enterprise' : '';
      }
      return clientType;
    },
  },
  actions: {
    // 设置用户的信息
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },
    // 重置用户信息
    resetInfo() {
      this.$reset();
    },
    // 获取用户信息
    async info() {
      this.setInfo({});
    },
    // Logout
    async logout() {
      this.resetInfo();
      clearToken();
    },
    // 小程序授权登录
    authLogin(provider, encryptedData, iv) {
      return new Promise((resolve, reject) => {
        uni.login({
          provider,
          success: async (result: UniApp.LoginRes) => {
            if (result.code) {
              resolve({});
              try{
                const res = await WxLogin({
                  code: result.code,
                  encryptedData: encryptedData,
                  iv: iv
                })
                if(res) {
                  this.$patch({
                    token: res.access_token,
                    expires: res.expires_in,
                    tokenType: res.token_type,
                  });
                }
              }catch (e) {
                console.log(e, '登陆失败')
              }
            }
            else {
              reject(new Error(result.errMsg));
            }
          },
          fail: (err: any) => {
            console.error(`login error: ${err}`);
            reject(err);
          },
        });
      });
    },
    // 登录
    async login() {
      const { access_token, token_type, expires_in } = await userLogin({
        // TODO 临时增加假的校验
        // phone: '18646897780',
        phone: '18666666666',
        password: '123123',
      });
      console.log('登录:::', access_token, token_type, expires_in);
      this.$patch({
        token: access_token,
        expires: expires_in,
        tokenType: token_type,
      });
    },
    // 获取用户信息
    async setUserInfo() {
      const info = await userUserInfo();
      const type = info.type;
      if (typeof type === 'number') {
        let clientType: ClientType = type === 1 ? 'customer' : [3, 4].includes(type) ? 'enterprise' : '';
        uni.setStorageSync('clientType', clientType)
      }
      this.$patch({
        info,
      });
    },
  },
  persist: {
    enabled: true,
  },
});

export default useUserStore;
